package com.jay.compass;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.jay.compass.adapter.MessageAdapter;
import com.jay.compass.app.StarApplication;
import com.jay.compass.base.MessageItem;
import com.jay.compass.base.RecentItem;
import com.jay.compass.ble.BluetoothLeService;
import com.jay.compass.bt.BluetoothService;
import com.jay.compass.bt.IBluetoothService;
import com.jay.compass.database.MessageDB;
import com.jay.compass.database.RecentDB;
import com.jay.compass.utils.SharePreferenceUtil;
import com.pzf.liaotian.xlistview.MsgListView;
import com.pzf.liaotian.xlistview.MsgListView.IXListViewListener;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class ChatActivity extends Activity implements OnTouchListener,
		IXListViewListener {

	private MessageDB mMsgDB;
	private RecentDB mRecentDB;
	private StarApplication mApplication;
	private MsgListView mMsgListView;
	private static MessageAdapter adapter;
	public static int MSGPAGERNUM;
	private SharePreferenceUtil mSpUtil;
	private String mUserId;
	private String mUserName = "";
	private TextView titleTextView;
	private Button sendButton;
	private EditText msgEditText;

	private int mConnectType = LoginActivity.CONNECT_TYPE_NONE;
	private int mConnectStatus = 0;
	private String mSendMsg;
	private ProgressDialog sendingDialog;
	private IBluetoothService bluetoothService;
	private Handler mSendHandler = new Handler();

	public BluetoothLeService mBluetoothLeService;

	private final BroadcastReceiver mBluetoothReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			final String actionString = intent.getAction();
			if (BluetoothService.ACTION_BLUETOOTH_CONNECTED
					.equals(actionString)) {

			} else if (BluetoothService.ACTION_BLUETOOTH_TIMEOUT
					.equals(actionString)) {
			} else if (BluetoothService.ACTION_BLUETOOTH_DISCONNECTED
					.equals(actionString)) {
				Toast.makeText(ChatActivity.this, "断开连接", Toast.LENGTH_SHORT)
						.show();
			} else if (BluetoothService.ACTION_BLUETOOTH_TOAST
					.equals(actionString)) {
				Toast.makeText(
						ChatActivity.this,
						intent.getStringExtra(BluetoothService.BROADCAST_TO_TOAST),
						Toast.LENGTH_SHORT).show();
			} else if (BluetoothService.ACTION_BLUETOOTH_NEW_MESSAGE
					.equals(actionString)) {
				String id = intent
						.getStringExtra(BluetoothService.NEW_MESSAGE_ID);
				String msg = intent
						.getStringExtra(BluetoothService.NEW_MESSAGE_MESSAGE);
				RecentItem item = new RecentItem(RecentItem.MESSAGE_TYPE_TEXT,
						id, StarApplication.getHeads()[Integer.valueOf(id
								.substring(id.length() - 1)) % 10], id, msg,
						StarApplication.getInstance().getRecentDB()
								.getRecentList().size(),
						System.currentTimeMillis(), 0);
				StarApplication.getInstance().getRecentDB().saveRecent(item);

				MessageItem msgItem = new MessageItem(
						MessageItem.MESSAGE_TYPE_TEXT, id,
						System.currentTimeMillis(), msg,
						StarApplication.getHeads()[Integer.valueOf(id
								.substring(id.length() - 1)) % 10], true, 1, 0);

				StarApplication.getInstance().getMessageDB()
						.saveMsg(id, msgItem);
				adapter.upDateMsg(msgItem);
			} else if (BluetoothService.ACTION_BLUETOOTH_SEND_SUCCESS
					.equals(actionString)) {
				if (sendingDialog.isShowing()) {
					sendingDialog.dismiss();
				}

				int headRes = StarApplication.getHeads()[Integer
						.valueOf(mUserId.substring(mUserId.length() - 1)) % 10];
				if (isMobileNum(mUserId)) {
					headRes = R.drawable.head_phone;
				} else {
					mUserName = mUserId;
				}
				
				RecentItem item = new RecentItem(RecentItem.MESSAGE_TYPE_TEXT,
						mUserId, headRes, mUserName, mSendMsg, StarApplication
								.getInstance().getRecentDB().getRecentList()
								.size(), System.currentTimeMillis(), 0);
				StarApplication.getInstance().getRecentDB().saveRecent(item);
				MessageItem msgItem = new MessageItem(
						MessageItem.MESSAGE_TYPE_TEXT, mUserName,
						System.currentTimeMillis(), mSendMsg, headRes, false,
						0, 0);
				adapter.upDateMsg(msgItem);
				StarApplication.getInstance().getMessageDB()
						.saveMsg(mUserId, msgItem);

				scrollToBottomListItem();
				msgEditText.setText("");

			} else if (BluetoothService.ACTION_BLUETOOTH_SEND_FAILED
					.equals(actionString)) {
				if (sendingDialog.isShowing()) {
					sendingDialog.dismiss();
				}
			}
		}
	};

	private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			final String action = intent.getAction();
			if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
				System.out.println("gatt connected");
			} else if (BluetoothLeService.ACTION_GATT_DISCONNECTED
					.equals(action)) {
				Toast.makeText(ChatActivity.this, "断开连接", Toast.LENGTH_SHORT)
						.show();
				// getActionBar().setTitle("未连接");
				// mConnectStatus = 0;
				// finish();
			} else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED
					.equals(action)) {
			} else if (BluetoothLeService.ACTION_DEVICE_FIND.equals(action)) {
				// mConnectStatus = 1;
				// getActionBar().setTitle("已连接");
				// if (btConnectDialog.isShowing()) {
				// btConnectDialog.dismiss();
				// }
				// mBluetoothLeService.sendCommand(SEND_TYPE_ICJC, null, null);
			} else if (BluetoothLeService.ACTION_GATT_TOAST.equals(action)) {
				Toast.makeText(
						ChatActivity.this,
						intent.getStringExtra(BluetoothLeService.BROADCAST_TO_TOAST),
						Toast.LENGTH_SHORT).show();
			} else if (BluetoothLeService.ACTION_GATT_NEW_MESSAGE
					.equals(action)) {
				String id = intent
						.getStringExtra(BluetoothService.NEW_MESSAGE_ID);
				String msg = intent
						.getStringExtra(BluetoothService.NEW_MESSAGE_MESSAGE);
				RecentItem item = new RecentItem(RecentItem.MESSAGE_TYPE_TEXT,
						id, StarApplication.getHeads()[Integer.valueOf(id
								.substring(id.length() - 1)) % 10], id, msg,
						StarApplication.getInstance().getRecentDB()
								.getRecentList().size(),
						System.currentTimeMillis(), 0);
				StarApplication.getInstance().getRecentDB().saveRecent(item);

				MessageItem msgItem = new MessageItem(
						MessageItem.MESSAGE_TYPE_TEXT, id,
						System.currentTimeMillis(), msg,
						StarApplication.getHeads()[Integer.valueOf(id
								.substring(id.length() - 1)) % 10], true, 1, 0);

				StarApplication.getInstance().getMessageDB()
						.saveMsg(id, msgItem);
				adapter.upDateMsg(msgItem);
			} else if (BluetoothLeService.ACTION_GATT_SEND_SUCCESS
					.equals(action)) {
				if (sendingDialog.isShowing()) {
					sendingDialog.dismiss();
				}

				int headRes = StarApplication.getHeads()[Integer
						.valueOf(mUserId.substring(mUserId.length() - 1)) % 10];
				if (isMobileNum(mUserId)) {
					headRes = R.drawable.head_phone;
				} else {
					mUserName = mUserId;
				}

				RecentItem item = new RecentItem(RecentItem.MESSAGE_TYPE_TEXT,
						mUserId, headRes, mUserName, mSendMsg,
						StarApplication.getInstance().getRecentDB()
								.getRecentList().size(),
						System.currentTimeMillis(), 0);
				StarApplication.getInstance().getRecentDB().saveRecent(item);
				MessageItem msgItem = new MessageItem(
						MessageItem.MESSAGE_TYPE_TEXT, mUserName,
						System.currentTimeMillis(), mSendMsg, headRes, false,
						0, 0);
				adapter.upDateMsg(msgItem);
				StarApplication.getInstance().getMessageDB()
						.saveMsg(mUserId, msgItem);

				scrollToBottomListItem();
				msgEditText.setText("");

			} else if (BluetoothLeService.ACTION_GATT_SEND_FAILED
					.equals(action)) {
				if (sendingDialog.isShowing()) {
					sendingDialog.dismiss();
				}
				Toast.makeText(ChatActivity.this, "发送失败", Toast.LENGTH_SHORT)
						.show();
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_chat);
		mUserId = getIntent().getStringExtra(FragmentChat.USER_ID);
		mUserName = getIntent().getStringExtra(FragmentChat.USER_NAME);
		
		System.out.println("user id = " + mUserId);
		System.out.println("user name = " + mUserName);
		
		mApplication = StarApplication.getInstance();
		mMsgDB = mApplication.getMessageDB();
		mRecentDB = mApplication.getRecentDB();
		mSpUtil = mApplication.getSpUtil();

		adapter = new MessageAdapter(this, initMsgData());
		mMsgListView = (MsgListView) findViewById(R.id.msg_listView);
		mMsgListView.setOnTouchListener(this);
		mMsgListView.setPullLoadEnable(false);
		mMsgListView.setXListViewListener(this);
		mMsgListView.setAdapter(adapter);
		mMsgListView.setSelection(adapter.getCount() - 1);
		initView();
		mConnectStatus = MainActivity.mConnectStatus;
		mConnectType = MainActivity.mConnectType;
		bluetoothService = mApplication.getBluetoothService();
		mBluetoothLeService = mApplication.getBleService();
		if (mConnectType == LoginActivity.CONNECT_TYPE_BLUETOOTH) {
			registerReceiver(mBluetoothReceiver, makeBluetoothIntentFilter());
			registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
		}
	}

	private static IntentFilter makeBluetoothIntentFilter() {
		final IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(BluetoothService.ACTION_BLUETOOTH_CONNECTED);
		intentFilter.addAction(BluetoothService.ACTION_BLUETOOTH_TIMEOUT);
		intentFilter.addAction(BluetoothService.ACTION_BLUETOOTH_DISCONNECTED);
		intentFilter.addAction(BluetoothService.ACTION_BLUETOOTH_TOAST);
		intentFilter.addAction(BluetoothService.ACTION_BLUETOOTH_NEW_MESSAGE);
		intentFilter.addAction(BluetoothService.ACTION_BLUETOOTH_SEND_SUCCESS);
		intentFilter.addAction(BluetoothService.ACTION_BLUETOOTH_SEND_FAILED);

		return intentFilter;
	}

	private static IntentFilter makeGattUpdateIntentFilter() {
		final IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED);
		intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED);
		intentFilter
				.addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED);
		intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE);
		intentFilter.addAction(BluetoothLeService.ACTION_DEVICE_FIND);
		intentFilter.addAction(BluetoothLeService.ACTION_GATT_TOAST);
		intentFilter.addAction(BluetoothLeService.ACTION_GATT_NEW_MESSAGE);
		intentFilter.addAction(BluetoothLeService.ACTION_GATT_SEND_SUCCESS);
		intentFilter.addAction(BluetoothLeService.ACTION_GATT_SEND_FAILED);

		return intentFilter;
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		System.out.println("+onResume+");

	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		System.out.println("+onPause+");
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		System.out.println("+onDestroy+");
		if (mConnectType == LoginActivity.CONNECT_TYPE_BLUETOOTH) {
			unregisterReceiver(mBluetoothReceiver);
			unregisterReceiver(mGattUpdateReceiver);
		}
	}

	private void initView() {
		titleTextView = (TextView) findViewById(R.id.chat_title_textview);
		if(!isMobileNum(mUserId)) {
			mUserName = "";
		}
		titleTextView.setText(mUserName + mUserId);
		sendButton = (Button) findViewById(R.id.send_btn);
		msgEditText = (EditText) findViewById(R.id.msg_et);

		sendButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				String message = msgEditText.getEditableText().toString();
				String id = mUserId;
				mSendMsg = message;

				if (message.length() < 1) {
					Toast.makeText(ChatActivity.this, "无法发送空的内容",
							Toast.LENGTH_SHORT).show();
					return;
				}

				if (isMobileNum(mUserId)) {
					message = "#" + mUserId + "#" + message;
					id = MainActivity.PHONE_BEIDOU_ID;
					System.out.println("is phone number");
				}

				if (mConnectStatus == 0) {
					Toast.makeText(ChatActivity.this, "请先连接设备",
							Toast.LENGTH_SHORT).show();
					return;
				}

				System.out.println("id = " + id);
				System.out.println("message = " + message);
				
				if (mConnectType == LoginActivity.CONNECT_TYPE_BLUETOOTH) {
					sendingDialog = ProgressDialog.show(ChatActivity.this,
							"发送中", "请稍后...");
					if (MainActivity.mBtType == MainActivity.BT_2_0) {
						bluetoothService.sendCommand(
								MainActivity.SEND_TYPE_TXSQ, id, message);
					} else if (MainActivity.mBtType == MainActivity.BT_4_0) {
						mBluetoothLeService.sendCommand(
								MainActivity.SEND_TYPE_TXSQ, id, message);
					}
					mSendHandler.postDelayed(new Runnable() {

						@Override
						public void run() {
							// TODO Auto-generated method stub
							if (sendingDialog.isShowing()) {
								sendingDialog.dismiss();
								Toast.makeText(ChatActivity.this, "发送超时",
										Toast.LENGTH_SHORT).show();
							}
						}
					}, 10000);
					if (!sendingDialog.isShowing())
						sendingDialog.show();
				}

			}
		});
	}

	private List<MessageItem> initMsgData() {
		List<MessageItem> list = mMsgDB.getMsg(mUserId, MSGPAGERNUM);
		System.out.println("list count = " + list.size());
		List<MessageItem> msgList = new ArrayList<MessageItem>();// 消息对象数组
		if (list.size() > 0) {
			for (MessageItem entity : list) {
				if (entity.getName().equals("")) {
					entity.setName("默认");
				}
				if (entity.getHeadImg() < 0) {
					entity.setHeadImg(0);
				}
				msgList.add(entity);
			}
		}
		return msgList;

	}

	/**
	 * @Description 滑动到列表底部
	 */
	private void scrollToBottomListItem() {
		// todo eric, why use the last one index + 2 can real scroll to the
		// bottom?
		if (mMsgListView != null) {
			mMsgListView.setSelection(adapter.getCount() + 1);
		}
	}

	@Override
	public void onRefresh() {
		// TODO Auto-generated method stub
		MSGPAGERNUM++;
		List<MessageItem> msgList = initMsgData();
		int position = adapter.getCount();
		adapter.setmMsgList(msgList);
		mMsgListView.stopRefresh();
		mMsgListView.setSelection(adapter.getCount() - position - 1);
	}

	@Override
	public void onLoadMore() {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean onTouch(View arg0, MotionEvent arg1) {
		// TODO Auto-generated method stub
		return false;
	}

	public boolean isMobileNum(String mobiles) {
		if (mobiles.length() < 5)
			return false;
		Pattern p = Pattern
				.compile("^((13[0-9])|(15[^4,\\D])|(18[0-9]))\\d{8}$");
		Matcher m = p.matcher(mobiles);
		return m.matches();
	}
}
